"""
Web管理界面路由
"""
from fastapi import APIRouter, Depends, Request, HTTPException, status
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from sqlalchemy import func
from typing import Optional, Dict, Any
import os
from datetime import datetime, timedelta

from core.database import get_db
from core.config import get_settings
from core.auth import get_current_user_from_token
from models.database import User, ParseTask, APILog
from core.logger import api_logger
from services.metrics_storage import MetricsStorageService

router = APIRouter()
settings = get_settings()

# 设置模板目录
templates = Jinja2Templates(directory="templates")


@router.get("/", response_class=HTMLResponse)
async def web_root(request: Request, token: Optional[str] = None, db: Session = Depends(get_db)):
    """Web管理界面根路径"""
    try:
        # 检查是否有token
        if token:
            try:
                current_user = get_current_user_from_token(token, db)
                # 获取基本统计信息
                stats = await get_dashboard_stats(db)
                return templates.TemplateResponse(
                    "dashboard.html",
                    {"request": request, "user": current_user, "stats": stats, "token": token}
                )
            except Exception:
                # Token无效，显示登录页面
                return templates.TemplateResponse("login.html", {"request": request})
        else:
            # 无token，显示登录页面
            return templates.TemplateResponse("login.html", {"request": request})
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/"})
        return templates.TemplateResponse("login.html", {"request": request})


@router.get("/login", response_class=HTMLResponse)
async def web_login(request: Request):
    """Web登录页面"""
    return templates.TemplateResponse("login.html", {"request": request})


@router.get("/dashboard", response_class=HTMLResponse)
async def web_dashboard(request: Request, token: str, db: Session = Depends(get_db)):
    """Web仪表板页面"""
    try:
        current_user = get_current_user_from_token(token, db)
        stats = await get_dashboard_stats(db)
        return templates.TemplateResponse(
            "dashboard.html",
            {"request": request, "user": current_user, "stats": stats, "token": token}
        )
    except HTTPException as e:
        api_logger.log_error(e, {"endpoint": "/web/dashboard"})
        return templates.TemplateResponse("login.html", {"request": request})
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/dashboard"})
        return templates.TemplateResponse("login.html", {"request": request})


@router.get("/upload", response_class=HTMLResponse)
async def web_upload(request: Request, token: str, db: Session = Depends(get_db)):
    """Web文档上传页面"""
    try:
        current_user = get_current_user_from_token(token, db)
        return templates.TemplateResponse(
            "upload.html",
            {"request": request, "user": current_user, "token": token}
        )
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/upload"})
        return templates.TemplateResponse("login.html", {"request": request})


@router.get("/tasks", response_class=HTMLResponse)
async def web_tasks(request: Request, token: str, db: Session = Depends(get_db)):
    """Web任务管理页面"""
    try:
        current_user = get_current_user_from_token(token, db)
        return templates.TemplateResponse(
            "tasks.html",
            {"request": request, "user": current_user, "token": token}
        )
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/tasks"})
        return templates.TemplateResponse("login.html", {"request": request})


@router.get("/slicing", response_class=HTMLResponse)
async def web_slicing(request: Request, token: str, db: Session = Depends(get_db)):
    """Web文档切片页面"""
    try:
        current_user = get_current_user_from_token(token, db)
        return templates.TemplateResponse(
            "slicing.html",
            {"request": request, "user": current_user, "token": token}
        )
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/slicing"})
        return templates.TemplateResponse("login.html", {"request": request})


@router.get("/users", response_class=HTMLResponse)
async def web_users(request: Request, token: str, db: Session = Depends(get_db)):
    """Web用户管理页面"""
    try:
        current_user = get_current_user_from_token(token, db)
        # 检查管理员权限
        if current_user.role != "admin":
            raise HTTPException(status_code=403, detail="权限不足")
        
        return templates.TemplateResponse(
            "users.html",
            {"request": request, "user": current_user, "token": token}
        )
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/users"})
        return templates.TemplateResponse("login.html", {"request": request})


@router.get("/logs", response_class=HTMLResponse)
async def web_logs(request: Request, token: str, db: Session = Depends(get_db)):
    """Web调用日志页面"""
    try:
        current_user = get_current_user_from_token(token, db)
        # 检查管理员权限
        if current_user.role != "admin":
            raise HTTPException(status_code=403, detail="权限不足")
        
        return templates.TemplateResponse(
            "logs.html",
            {"request": request, "user": current_user, "token": token}
        )
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/logs"})
        return templates.TemplateResponse("login.html", {"request": request})


@router.get("/settings", response_class=HTMLResponse)
async def web_settings(request: Request, token: str, db: Session = Depends(get_db)):
    """Web系统设置页面"""
    try:
        current_user = get_current_user_from_token(token, db)
        # 检查管理员权限
        if current_user.role != "admin":
            raise HTTPException(status_code=403, detail="权限不足")
        
        return templates.TemplateResponse(
            "settings.html",
            {"request": request, "user": current_user, "token": token}
        )
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/settings"})
        return templates.TemplateResponse("login.html", {"request": request})


@router.get("/monitoring", response_class=HTMLResponse)
async def web_monitoring(request: Request, token: str, db: Session = Depends(get_db)):
    """Web系统监控页面"""
    try:
        current_user = get_current_user_from_token(token, db)
        
        # 获取监控配置
        metrics_config = MetricsStorageService.get_metrics_config()
        
        return templates.TemplateResponse(
            "system_monitoring.html",
            {"request": request, "user": current_user, "token": token, "metrics_config": metrics_config}
        )
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/web/monitoring"})
        return templates.TemplateResponse("login.html", {"request": request})


async def get_dashboard_stats(db: Session) -> Dict[str, Any]:
    """获取仪表板统计信息"""
    try:
        # 用户统计
        total_users = db.query(User).count()
        active_users = db.query(User).filter(User.is_active == True).count()
        
        # 任务统计
        total_tasks = db.query(ParseTask).count()
        completed_tasks = db.query(ParseTask).filter(ParseTask.status == "completed").count()
        processing_tasks = db.query(ParseTask).filter(ParseTask.status == "processing").count()
        failed_tasks = db.query(ParseTask).filter(ParseTask.status == "failed").count()
        
        # 今日统计
        today = datetime.now().date()
        today_tasks = db.query(ParseTask).filter(func.date(ParseTask.created_at) == today).count()
        
        # 昨日统计（用于计算增长率）
        yesterday = today - timedelta(days=1)
        yesterday_tasks = db.query(ParseTask).filter(func.date(ParseTask.created_at) == yesterday).count()
        
        # 计算今日任务增长率
        today_growth_rate = 0
        if yesterday_tasks > 0:
            today_growth_rate = round(((today_tasks - yesterday_tasks) / yesterday_tasks) * 100, 1)
        elif today_tasks > 0:
            today_growth_rate = 100.0  # 昨天为0，今天有任务，显示100%增长
        
        # 计算进行中任务的变化率（基于最近1小时）
        one_hour_ago = datetime.now() - timedelta(hours=1)
        recent_processing_tasks = db.query(ParseTask).filter(
            ParseTask.status == "processing",
            ParseTask.started_at >= one_hour_ago
        ).count()
        
        # 成功率
        success_rate = (completed_tasks / total_tasks * 100) if total_tasks > 0 else 0
        
        # 系统状态 - 从系统监控服务获取
        try:
            from services.system_monitor import SystemMonitorService
            system_status = SystemMonitorService.get_system_status()
            system_uptime = SystemMonitorService.format_uptime(SystemMonitorService.get_cached_metrics(1)["uptime"])
        except Exception:
            system_status = "正常"
            system_uptime = "运行中"
        
        # 最近7天统计（用于图表）
        week_ago = today - timedelta(days=7)
        week_stats = []
        for i in range(7):
            date = week_ago + timedelta(days=i)
            date_tasks = db.query(ParseTask).filter(func.date(ParseTask.created_at) == date).count()
            date_completed = db.query(ParseTask).filter(
                func.date(ParseTask.created_at) == date,
                ParseTask.status == "completed"
            ).count()
            date_failed = db.query(ParseTask).filter(
                func.date(ParseTask.created_at) == date,
                ParseTask.status == "failed"
            ).count()
            
            week_stats.append({
                "date": date.strftime("%Y-%m-%d"),
                "tasks": date_tasks,
                "completed": date_completed,
                "failed": date_failed
            })
        
        return {
            "users": {
                "total": total_users,
                "active": active_users,
                "today": today_tasks
            },
            "tasks": {
                "total": total_tasks,
                "completed": completed_tasks,
                "processing": processing_tasks,
                "failed": failed_tasks,
                "today": today_tasks,
                "success_rate": round(success_rate, 2),
                "today_growth_rate": today_growth_rate,
                "recent_processing": recent_processing_tasks
            },
            "system": {
                "status": system_status,
                "uptime": system_uptime
            },
            "week_stats": week_stats
        }
    except Exception as e:
        api_logger.log_error(e, {"function": "get_dashboard_stats"})
        return {
            "users": {"total": 0, "active": 0, "today": 0},
            "tasks": {"total": 0, "completed": 0, "processing": 0, "failed": 0, "today": 0, "success_rate": 0, "today_growth_rate": 0, "recent_processing": 0},
            "system": {"status": "异常", "uptime": "未知"},
            "week_stats": []
        }


# 导出路由器
web_router = router